package com.ferry.lock.engine.zookeeper.menagerie;

import java.io.*;

/**
 * Created by daiyong
 */
public class JavaSerializer<T extends Serializer> implements Serializer<T>  {

	@Override
	public byte[] serializer(T instance) {
		try {
			ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream();
			ObjectOutputStream arrayOutput = new ObjectOutputStream(byteArrayStream);
			arrayOutput.writeObject(instance);
			arrayOutput.flush();

			byte[] bytes = byteArrayStream.toByteArray();
			arrayOutput.close();
			return bytes;

		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public T deserializer(byte[] data) {
		try {
			ObjectInputStream inputStream  = new ObjectInputStream(new ByteArrayInputStream(data));
			return (T)inputStream.readObject();
		} catch (IOException e) {
			throw new RuntimeException(e);
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e);
		}
	}

}
